﻿package com.huanying.goodjob.job;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.huanying.framework.BaseController;
import com.huanying.framework.PageBean;
import com.huanying.framework.user.User;
import com.huanying.framework.user.UserService;
import com.huanying.framework.utils.PushtoSingle;
import com.huanying.goodjob.community.Area;
import com.huanying.goodjob.community.CommunityService;
import com.huanying.goodjob.jobtype.JobtypeService;
import com.huanying.goodjob.message.Message;
import com.huanying.goodjob.message.MessageService;
import com.huanying.goodjob.skill.Skill;


import java.util.Collections;

import java.util.Comparator;
@Controller
public class JobController extends BaseController {

	@Autowired
	private JobService jobService;
	@Autowired
	private UserService userService;
	@Autowired
	private JobtypeService jobtypeService;
	@Autowired
	private CommunityService communityService;
	@Autowired
	private MessageService messageService;

	private static Logger logger = Logger.getLogger(JobController.class);

	// 后台，管理全部工作
	@RequestMapping(value = "/show_job.do")
	public String show(String user_name, String community_name, String create_time, String decoration_type,
			String release_status, String status, String page_num, Model model) {
		PageBean pageBean = null;
		Map<String, String> map = new HashMap<String, String>();
		map.put("user_name", user_name);
		map.put("community_name", community_name);
		map.put("create_time", create_time);
		map.put("decoration_type", decoration_type);
		map.put("release_status", release_status);
		map.put("status", status);
		if (page_num == null) {
			page_num = "1";
		}

		try {
			pageBean = jobService.searchJobs(map, super.getPageSize(), Integer.valueOf(page_num));
		} catch (NumberFormatException e) {
			logger.error("查询工作失败", e);
		} catch (Exception e) {
			logger.error("查询工作失败", e);
		}

		model.addAttribute("day",create_time);
		model.addAttribute("user_name", user_name);
		model.addAttribute("community_name", community_name);
		model.addAttribute("create_time", create_time);
		model.addAttribute("decoration_type", decoration_type);
		model.addAttribute("release_status", release_status);
		model.addAttribute("status", status);
		
		model.addAttribute("jobs", pageBean.getList());
		model.addAttribute("page", pageBean);

		return "job/add_job";
	}

	// 后台，管理工作详情
	@RequestMapping(value = "/get_job.do", method = RequestMethod.GET)
	public String get_job(String id, String page_num, Model model) {
		PageBean pageBean = null;
		Map<String, String> map = new HashMap<String, String>();
		map.put("job_id", id);
		if (page_num == null) {
			page_num = "1";
		}
		try {
			pageBean = jobService.searchJobitems(map, super.getPageSize(), Integer.valueOf(page_num));
			Job j = jobService.getbyId_job(Integer.valueOf(id));
			model.addAttribute("job", j);
		} catch (Exception e) {
			logger.error("查询工作详情失败", e);
		}
		model.addAttribute("jobitems", pageBean.getList());
		model.addAttribute("page", pageBean);
		return "job/job_detail";
	}

	// 后台，管理接单详情
	@RequestMapping(value = "/get_jobitem.do", method = RequestMethod.GET)
	public String get(String id, String page_num, Model model) {
		PageBean pageBean = null;
		Map<String, String> map = new HashMap<String, String>();
		map.put("jobitem_id", id);
		if (page_num == null) {
			page_num = "1";
		}
		try {
			pageBean = jobService.searchJobitem_Users(map, super.getPageSize(), Integer.valueOf(page_num));
			Jobitem j = jobService.getbyId_jobitem(Integer.valueOf(id));
			model.addAttribute("jobitem", j);
		} catch (Exception e) {
			logger.error("查询工作项失败", e);
		}
		model.addAttribute("jobitem_users", pageBean.getList());
		model.addAttribute("page", pageBean);
		return "job/jobitem_user";
	}

	// 后台，修改工作状态
	@RequestMapping(value = "/update_job_status.do", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, String> job_status(String id, int status) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			Job job = jobService.getbyId_job(Integer.valueOf(id));
			job.setStatus(status);
			jobService.update_job(job);
			map.put("flag", "1");
			map.put("status", String.valueOf(job.getStatus()));
		} catch (Exception e) {
			logger.error("修改工作状态失败", e);
			map.put("flag", "0");
		}
		return map;
	}

	// 后台，修改工作项状态
	@RequestMapping(value = "/update_jobitem_status.do", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, String> jobitem_status(String id, int status) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			Jobitem jobitem = jobService.getbyId_jobitem(Integer.valueOf(id));
			jobitem.setStatus(status);
			jobService.update_jobitem(jobitem);
			map.put("flag", "1");
			map.put("status", String.valueOf(jobitem.getStatus()));
		} catch (Exception e) {
			logger.error("修改工作项状态失败", e);
			map.put("flag", "0");
		}
		return map;
	}

	// 发布新工作,判断能否发布工作
	@RequestMapping(value = "/add_job.do", method = RequestMethod.GET)
	@ResponseBody
	public String save_job(String user_id, String area_code, String community_name, String jobtype_id, String skills_id,
			String decoration_type, String area, String unit, String salary, String urgent_status, String urgent_fee,
			String pre_start_date, String jsoncallback) {
		Map<String, String> map = new HashMap<String, String>();
		
		try {
			User user = userService.getbyId(Integer.valueOf(user_id));
			if (user.getBeans() > 0) {
				// 判断能否发布工作
				logger.info("该用户可以发布新工作");

				Job job = new Job();
				Jobitem jobitem = new Jobitem();
				job.setUser(user);
				if (decoration_type != null && decoration_type != "") {
					job.setDecoration_type(Integer.valueOf(decoration_type));
				}
				if (area_code != null && area_code != "") {
					if (area_code.contains("_")) {
						area_code = area_code.substring(1, area_code.length());
						area_code = communityService.getCounty_bystring(area_code);
					}
					Area county = communityService.getbyCode(area_code);
					if (county != null) {
						job.setArea(county);
					}

				}
				if (community_name != null && community_name != "") {
					job.setCommunity(community_name);
				}
				if (job != null) {
					job.setStatus(1);
					job.setJob_status(0);
					job.setRelease_status(1);
					job.setCreate_time(new Date());
					jobitem.setJob(job);
				}
				if (jobtype_id != null && jobtype_id != "") {
					jobitem.setJobtype(jobtypeService.getbyId_jobtype(Integer.valueOf(jobtype_id)));// 根据工种ID查找工种
				}
				if (pre_start_date != null && pre_start_date != "") {
					DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
					jobitem.setPre_start_date(format1.parse(pre_start_date));
				}
				if (area != null && area != "") {
					jobitem.setArea(Double.valueOf(area));
				}
				if (unit != null && unit != "") {
					jobitem.setUnit(Integer.valueOf(unit));
				}
				if (salary != null && salary != "") {
					jobitem.setSalary(Double.valueOf(salary));
				}
				if (urgent_status != null && urgent_status != "") {
					jobitem.setUrgent_status(Integer.valueOf(urgent_status));
				}
				if (urgent_fee != null && urgent_fee != "") {
					jobitem.setUrgent_fee(Double.valueOf(urgent_fee));
				}
				jobitem.setStatus(1);
				int id = jobService.add_jobitem(jobitem);
				// 添加技能
				if (skills_id != null && skills_id != "") {
					String[] skillid_array = skills_id.split("_");
					if (id != 0) {
						jobService.add_skills(id, skillid_array);
					}
				}
				user.setBeans(user.getBeans() - 1);
				userService.update(user);
				userService.addCache(user);
				map.put("flag", "1");
				map.put("jobitemid", String.valueOf(jobitem.getId()));
			} else {
				logger.error("用户金额不足，无法发布");
				map.put("flag", "2");
			}
		} catch (Exception e) {
			logger.error("发布新工作失败", e);
			map.put("flag", "0");
		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}

	@RequestMapping(value = "/add_jobitem.do", method = RequestMethod.GET)
	@ResponseBody
	// 前台，在原来的工作中添加工作项
	public String save_jobitem(String job_id, String jobtype_id, String skills_id, String area, String unit,
			String salary, String urgent_status, String urgent_fee, String pre_start_date, String jsoncallback) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			Job job = jobService.getbyId_job(Integer.valueOf(job_id));
			User user = userService.getbyId(Integer.valueOf(job.getUser().getId()));
			if (user.getBeans() > 0) {
				// 判断能否发布工作
				logger.info("该用户可以发布新工作");

				Jobitem jobitem = new Jobitem();
				jobitem.setJob(job);
				if (jobtype_id != null && jobtype_id != "") {
					jobitem.setJobtype(jobtypeService.getbyId_jobtype(Integer.valueOf(jobtype_id)));// 根据工种ID查找工种
				}
				if (pre_start_date != null && pre_start_date != "") {
					DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
					jobitem.setPre_start_date(format1.parse(pre_start_date));
				}
				if (area != null && area != "") {
					jobitem.setArea(Double.valueOf(area));
				}
				if (unit != null && unit != "") {
					jobitem.setUnit(Integer.valueOf(unit));
				}
				if (salary != null && salary != "") {
					jobitem.setSalary(Double.valueOf(salary));
				}
				if (urgent_status != null && urgent_status != "") {
					jobitem.setUrgent_status(Integer.valueOf(urgent_status));
				}
				if (urgent_fee != null && urgent_fee != "") {
					jobitem.setUrgent_fee(Double.valueOf(urgent_fee));
				}
				jobitem.setStatus(1);
				jobService.add_jobitem(jobitem);
				if (skills_id != null && skills_id != "") {
					String[] skillid_array = skills_id.split("_");
					if (jobitem.getId() != 0) {
						jobService.add_skills(jobitem.getId(), skillid_array);
					}
				}
				user.setBeans(user.getBeans() - 1);
				userService.update(user);
				userService.addCache(user);
				map.put("flag", "1");
				map.put("id", String.valueOf(jobitem.getId()));
			} else {
				map.put("flag", "2");
				logger.info("用户金额不足，无法发单");
			}
		} catch (Exception e) {
			logger.error("添加工作失败", e);
			map.put("flag", "0");
		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}

	// 删除jobitem
	@RequestMapping(value = "/delete_jobitem.do", method = RequestMethod.GET)
	@ResponseBody
	public String delete_jobitem(String jobitem_id, String jsoncallback) {
		Map<String, String> map = new HashMap<String, String>();
		if (jobitem_id != null) {
			Jobitem jobitem;
			try {
				jobitem = jobService.getbyId_jobitem(Integer.valueOf(jobitem_id));
				jobitem.setStatus(0);
				jobService.update_jobitem(jobitem);

				map.put("flag", "1");

			} catch (NumberFormatException e) {
				logger.error("删除jobitem失败", e);
				map.put("flag", "0");
			} catch (Exception e) {
				logger.error("删除jobitem失败", e);
				map.put("flag", "0");
			}
		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}

	// 删除job
	@RequestMapping(value = "/delete_job.do", method = RequestMethod.GET)
	@ResponseBody
	public String delete_job(String job_id, String jsoncallback) {
		Map<String, String> map = new HashMap<String, String>();
		if (job_id != null) {
			Job job;
			try {
				job = jobService.getbyId_job(Integer.valueOf(job_id));
				job.setStatus(0);
				jobService.update_job(job);
				map.put("flag", "1");
			} catch (NumberFormatException e) {
				logger.error("删除job失败", e);
				map.put("flag", "0");
			} catch (Exception e) {
				logger.error("删除job失败", e);
				map.put("flag", "0");
			}
		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}

	// 前台，接单,判断用户是否还能接单+避免重复接单
	@RequestMapping(value = "/add_jobitem_user.do", method = RequestMethod.GET)
	@ResponseBody
	public String add_jobitem_user(String user_id, String jobitem_id, String jsoncallback) {
		Map<String, String> map = new HashMap<String, String>();
		Map<String, String> map1 = new HashMap<String, String>();
		List<Object> list = new ArrayList<Object>();
		try {
			// 判断是否重复接单
			map1.put("user_id", user_id);
			map1.put("jobitem_id", jobitem_id);
			map1.put("status", "1");
			list = jobService.searchJobitem_Users(map1);
			if (list.size() == 0) {
				Jobitem_User jobitem_user = new Jobitem_User();
				User user = userService.getbyId(Integer.valueOf(user_id));
				Jobitem jobitem = jobService.getbyId_jobitem(Integer.valueOf(jobitem_id));
				jobitem.setJobitem_status(2);
				jobitem_user.setJobitem(jobitem);
				jobitem_user.setUser(user);
				jobitem_user.setCreate_time(new Date());
				jobitem_user.setStatus(1);
				if (user.getBeans() > 0) {
					// 判断用户是否还能接单
					jobService.add_jobitem_user(jobitem_user);
					user.setBeans(user.getBeans() - 1);
					userService.update(user);
					userService.addCache(user);
					map.put("flag", "1");
					map.put("jobitem_user_id", String.valueOf(jobitem_user.getId()));

					// 添加工作项状态日志
					Jobitemstatus_Change jobitemstatus_change = new Jobitemstatus_Change();
					jobitemstatus_change.setJobitem(jobitem);
					jobitemstatus_change.setJobitem_status(2);
					jobitemstatus_change.setTime(new Date());
					jobitemstatus_change.setStatus(1);
					jobService.add_jobitemstatus_change(jobitemstatus_change);
					
					// 发送消息
					Message message = new Message();
					User sender  = userService.getbyId(jobitem_user.getUser().getId());
					User receiver = userService.getbyId(jobitem_user.getJobitem().getJob().getUser().getId());
					message.setSender(sender);
					message.setReceiver(receiver);
					message.setJobitem(jobitem_user.getJobitem());
					message.setStatus(1);
					message.setReceiver_type(2);
					message.setIssystemmessage(1);
					message.setMessage("您的发布已被选中");
					message.setCheckstatus(0);
					messageService.add_message(message);
					
					// 推送
					PushtoSingle.pushApp(receiver.getClientid(), message);
					if (receiver.getToken() != null && !("undefined").equals(receiver.getToken())) {
						PushtoSingle.pushApp(receiver.getToken(), message);
					}
					
				} else {
					logger.info("工人余额不足，接单失败");
					map.put("flag", "2"); // 余额不足
				}
			} else {
				logger.info("不能重复接单");
				map.put("flag", "3");
			}
		} catch (Exception e) {
			logger.error("工人接单失败", e);
			map.put("flag", "0");
		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}

	// 前台，取消接单/退单(被抢、等待开工),双方都看不到
	@RequestMapping(value = "/delete_jobitem_user.do", method = RequestMethod.GET)
	@ResponseBody
	public String delete_jobitem_user(String jobitem_user_id, String jsoncallback) {
		Map<String, String> map = new HashMap<String, String>();
		Map<String, String> map1 = new HashMap<String, String>();
		List<Object> list1 = new ArrayList<Object>();
		Jobitem_User jobitem_user;
		try {
			jobitem_user = jobService.getbyId_jobitem_user(Integer.valueOf(jobitem_user_id));
			jobService.delete_jobitem_user(jobitem_user);

			User user = jobitem_user.getUser();

			// 修改jobitem的状态
			map1.put("status", "1");
			map1.put("jobitem_id", String.valueOf(jobitem_user.getJobitem().getId()));
			list1 = jobService.searchJobitem_Users(map1);
			if (list1.size() == 0) {
				jobitem_user.getJobitem().setJobitem_status(0);
				jobService.update_jobitem_user(jobitem_user);
			} else {
				Jobitem_User jobitem_user_tmp;
				/*jobitem_user_tmp.setStatus(0);*/
				jobitem_user.getJobitem().setJobitem_status(2);
				jobitem_user.setJobitem_status(0);
				
				for (int i = 0; i < list1.size(); i++) {
					
					jobitem_user_tmp = (Jobitem_User) list1.get(i);
					if(jobitem_user_tmp.getUser().getId()==Integer.valueOf(jobitem_user_id)){
						jobitem_user_tmp.setStatus(0);
					}
					jobitem_user.setJobitem_status(0);
					jobitem_user_tmp.setJobitem_status(0);
					jobService.update_jobitem_user(jobitem_user_tmp);
					
				}
				jobService.update_jobitem_user(jobitem_user);
			}
			
			// 发送消息
			Message message = new Message();
			User sender  = userService.getbyId(jobitem_user.getUser().getId());
			User receiver = userService.getbyId(jobitem_user.getJobitem().getJob().getUser().getId());
			message.setSender(sender);
			message.setReceiver(receiver);
			message.setJobitem(jobitem_user.getJobitem());
			message.setStatus(1);
			message.setReceiver_type(2);
			message.setIssystemmessage(1);
			message.setMessage("工人已退单");
			message.setCheckstatus(0);
			messageService.add_message(message);
			
			// 推送
			PushtoSingle.pushApp(receiver.getClientid(), message);
			if (receiver.getToken() != null && !("undefined").equals(receiver.getToken())) {
				PushtoSingle.pushApp(receiver.getToken(), message);
			}
			
			// 判断是否给用户加豆
			SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD");
			Date datenow = new Date();
			Date date1 = jobitem_user.getCreate_time();
			if (format.format(datenow).equals(format.format(date1))) {
				user.setBeans(user.getBeans() + 1);
				userService.update(user);
				userService.addCache(user);
			}
			map.put("flag", "1");
		} catch (Exception e) {
			logger.error("工人取消接单失败", e);
			map.put("flag", "0");
		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}

	// 前台，工长确定一个工人，被选中的订单 1，落选的订单 2，jobitem 3，添加一条日志
	@RequestMapping(value = "/ensure_user.do", method = RequestMethod.GET)
	@ResponseBody
	public String ensure_user(String jobitem_user_id, String jsoncallback) {
		Map<String, String> map = new HashMap<String, String>();
		List<Jobitem_User> list = null;
		try {
			Jobitem_User jobitem_user = jobService.getbyId_jobitem_user(Integer.valueOf(jobitem_user_id));
			list = jobService.getbyjobitem_id_jobitem_user(Integer.valueOf(jobitem_user.getJobitem().getId()));
			for (Jobitem_User jobitem_user_tmp : list) {
				Jobitem jobitem = jobService.getbyId_jobitem(jobitem_user.getJobitem().getId());
				if (jobitem_user_tmp.getId() == jobitem_user.getId()) {
					// 被选中
					jobitem_user.setJobitem_status(1);
					jobService.update_jobitem_user(jobitem_user_tmp);

					jobitem.setJobitem_status(3);
					jobitem_user.setJobitem(jobitem);
					jobService.update_jobitem_user(jobitem_user);

					// 添加工作项状态日志
					Jobitemstatus_Change jobitemstatus_change = new Jobitemstatus_Change();
					jobitemstatus_change.setJobitem(jobitem);
					jobitemstatus_change.setJobitem_status(3);
					jobitemstatus_change.setTime(new Date());
					jobitemstatus_change.setStatus(1);
					jobService.add_jobitemstatus_change(jobitemstatus_change);

					// 发送消息
					Message message = new Message();
					User receiver = userService.getbyId(jobitem_user.getUser().getId());
					User sender = userService.getbyId(jobitem_user.getJobitem().getJob().getUser().getId());
					message.setSender(sender);
					message.setReceiver(receiver);
					message.setJobitem(jobitem_user.getJobitem());
					message.setStatus(1);
					message.setIssystemmessage(1);
					message.setMessage("恭喜您被工长选中了");
					message.setCheckstatus(0);
					messageService.add_message(message);

					// 推送
					PushtoSingle.pushApp(receiver.getClientid(), message);
					if (receiver.getToken() != null && !("undefined").equals(receiver.getToken())) {
						PushtoSingle.pushApp(receiver.getToken(), message);
					}
				} else {
					// 未被选中
				    System.out.println("tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt"+jobitem_user_tmp.getJobitem_status());
					
				    if(jobitem_user_tmp.getStatus()==0){//jobitem_user_tmp.getJobitem_status()==0&&jobitem.getJobitem_status()==3
						continue;	
					}else{
						jobitem_user_tmp.setJobitem_status(2);
						jobService.update_jobitem_user(jobitem_user_tmp);
						
						// 发送消息
						Message message = new Message();
						User receiver = userService.getbyId(jobitem_user_tmp.getUser().getId());//jobitem_user.getUser().getId()
						User sender = userService.getbyId(jobitem_user.getJobitem().getJob().getUser().getId());
						message.setSender(sender);
						message.setReceiver(receiver);
						message.setJobitem(jobitem_user.getJobitem());
						message.setStatus(1);
						message.setIssystemmessage(1);
						message.setMessage("您没有被选中哦");
						message.setCheckstatus(0);
						messageService.add_message(message);
	
						// 推送
						PushtoSingle.pushApp(receiver.getClientid(), message);
						if (receiver.getToken() != null && !("undefined").equals(receiver.getToken())) {
							PushtoSingle.pushApp(receiver.getToken(), message);
						}
					}
				    	
						
					
				}
			}
			
			
			
			map.put("flag", "1");
		} catch (Exception e) {
			logger.error("工长确定工人失败", e);
			map.put("flag", "0");
		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}

	// 前台，工长发起开工请求，jobitem 5，添加一条日志
	@RequestMapping(value = "/start_request.do", method = RequestMethod.GET)
	@ResponseBody
	public String start_request(String jobitem_user_id, String jsoncallback) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			Jobitem_User jobitem_user = jobService.getbyId_jobitem_user(Integer.valueOf(jobitem_user_id));
			Jobitem jobitem = jobService.getbyId_jobitem(jobitem_user.getJobitem().getId());
			jobitem.setJobitem_status(5);
			jobitem_user.setJobitem(jobitem);
			jobService.update_jobitem_user(jobitem_user);

			// 添加工作项状态日志
			Jobitemstatus_Change jobitemstatus_change = new Jobitemstatus_Change();
			jobitemstatus_change.setJobitem(jobitem);
			jobitemstatus_change.setJobitem_status(5);
			jobitemstatus_change.setTime(new Date());
			jobitemstatus_change.setStatus(1);
			jobService.add_jobitemstatus_change(jobitemstatus_change);

			// 发送消息
			Message message = new Message();
			User receiver = userService.getbyId(jobitem_user.getUser().getId());
			User sender = userService.getbyId(jobitem_user.getJobitem().getJob().getUser().getId());
			message.setSender(sender);
			message.setReceiver(receiver);
			message.setJobitem(jobitem_user.getJobitem());
			message.setStatus(1);
			message.setIssystemmessage(1);
			message.setMessage("工长发出开工请求，请及时点击确认");
			message.setCheckstatus(0);
			messageService.add_message(message);

			// 推送
			PushtoSingle.pushApp(receiver.getClientid(), message);
			if (receiver.getToken() != null && !("undefined").equals(receiver.getToken())) {
				PushtoSingle.pushApp(receiver.getToken(), message);
			}
			map.put("flag", "1");
		} catch (Exception e) {
			logger.error("工长发起开工请求失败", e);
			map.put("flag", "0");
		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}

	// 前台，工人确定开工，jobitem 1，添加一条日志
	@RequestMapping(value = "/start_response.do", method = RequestMethod.GET)
	@ResponseBody
	public String start_response(String jobitem_user_id, String jsoncallback) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			Jobitem_User jobitem_user = jobService.getbyId_jobitem_user(Integer.valueOf(jobitem_user_id));
			Jobitem jobitem = jobService.getbyId_jobitem(jobitem_user.getJobitem().getId());
			jobitem.setJobitem_status(1);
			jobitem.setStart_date(new Date());
			jobitem_user.setJobitem(jobitem);
			jobService.update_jobitem_user(jobitem_user);

			// 添加工作项状态日志
			Jobitemstatus_Change jobitemstatus_change = new Jobitemstatus_Change();
			jobitemstatus_change.setJobitem(jobitem);
			jobitemstatus_change.setJobitem_status(1);
			jobitemstatus_change.setTime(new Date());
			jobitemstatus_change.setStatus(1);
			jobService.add_jobitemstatus_change(jobitemstatus_change);

			// 发送消息
			Message message = new Message();
			User sender = userService.getbyId(jobitem_user.getUser().getId());
			User receiver = userService.getbyId(jobitem_user.getJobitem().getJob().getUser().getId());
			message.setSender(sender);
			message.setReceiver(receiver);
			message.setJobitem(jobitem_user.getJobitem());
			message.setStatus(1);
			message.setReceiver_type(2);
			message.setIssystemmessage(1);
			message.setMessage("工人已确认开工");
			message.setCheckstatus(0);
			messageService.add_message(message);

			// 推送
			PushtoSingle.pushApp(receiver.getClientid(), message);
			if (receiver.getToken() != null && !("undefined").equals(receiver.getToken())) {
				PushtoSingle.pushApp(receiver.getToken(), message);
			}

			map.put("flag", "1");
		} catch (Exception e) {
			logger.error("工人确定开工失败", e);
			map.put("flag", "0");
		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}

	// 前台，工人普通完工请求,不需要传照片
	@RequestMapping(value = "/end_request.do", method = RequestMethod.GET)
	@ResponseBody
	public String end_request(String jobitem_user_id, String jsoncallback) throws InterruptedException {
		Map<String, String> map = new HashMap<String, String>();
		String str = "";
		Gson gson = new Gson();
		SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");
		Date date = new Date();
		try {
			Jobitem_User jobitem_user = jobService.getbyId_jobitem_user(Integer.valueOf(jobitem_user_id));
			Jobitem jobitem = jobService.getbyId_jobitem(jobitem_user.getJobitem().getId());
			jobitem.setJobitem_status(4);
			jobitem.setEnd_request_date(date);
			jobitem_user.setJobitem(jobitem);
			jobService.update_jobitem_user(jobitem_user);

			// 添加工作项状态日志
			Jobitemstatus_Change jobitemstatus_change = new Jobitemstatus_Change();
			jobitemstatus_change.setJobitem(jobitem);
			jobitemstatus_change.setJobitem_status(4);
			jobitemstatus_change.setTime(date);
			jobitemstatus_change.setStatus(1);
			jobService.add_jobitemstatus_change(jobitemstatus_change);

			// 发送消息
			Message message = new Message();
			User sender = userService.getbyId(jobitem_user.getUser().getId());
			User receiver = userService.getbyId(jobitem_user.getJobitem().getJob().getUser().getId());
			message.setSender(sender);
			message.setReceiver(receiver);
			message.setJobitem(jobitem_user.getJobitem());
			message.setStatus(1);
			message.setIssystemmessage(1);
			message.setMessage("工人发起完工请求");
			message.setReceiver_type(2);
			message.setCheckstatus(0);
			messageService.add_message(message);

			// 推送
			PushtoSingle.pushApp(receiver.getClientid(), message);
			if (receiver.getToken() != null && !("undefined").equals(receiver.getToken())) {
				PushtoSingle.pushApp(receiver.getToken(), message);
			}

			map.put("flag", "1");
			map.put("time", String.valueOf(format.format(jobitemstatus_change.getTime())));
		} catch (Exception e) {
			logger.error("工人完工请求失败", e);
			map.put("flag", "0");
		}
		str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}

	// 前台，工人返工完工请求,需要传照片
	@RequestMapping(value = "/end_request_rework.do", method = RequestMethod.POST)
	@ResponseBody
	public String end_request_rework(String jobitem_user_id, String memo,
			@RequestParam("img_url1") MultipartFile img_url1, MultipartFile img_url2,MultipartFile img_url3) throws InterruptedException {
		Map<String, String> map = new HashMap<String, String>();
		String filePath = null, file_name = null;
		SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");
		Date date = new Date();
		Gson gson = new Gson();
		try {
			Jobitem_User jobitem_user = jobService.getbyId_jobitem_user(Integer.valueOf(jobitem_user_id));
			Jobitem jobitem = jobService.getbyId_jobitem(jobitem_user.getJobitem().getId());
			jobitem.setJobitem_status(4);
			jobitem.setEnd_request_date(date);
			jobitem_user.setJobitem(jobitem);
			jobService.update_jobitem_user(jobitem_user);
			Rework rework = new Rework();
			if (!img_url1.isEmpty()&&!img_url1.equals("")&&img_url1!=null&&img_url1.getSize()!=0) {
				// 获得上传时的文件名
				String temp_name = img_url1.getOriginalFilename();
				String postfix = temp_name.substring(temp_name.lastIndexOf("."), temp_name.length());
				file_name = UUID.randomUUID().toString() + postfix;
				filePath = super.getSession().getServletContext().getRealPath("")+"fileUpload"+File.separator+"job"+File.separator +file_name;
				logger.info(filePath);
				try {
					img_url1.transferTo(new File(filePath));
					logger.info("You successfully uploaded img_url1");
				} catch (Exception e) {
					logger.error("You failed to upload", e);
					map.put("flag", "3");
					return gson.toJson(map);
				}
				String realfliePath = "fileUpload" + File.separator + "job" + File.separator + file_name;					
				rework.setImg_url(realfliePath);
			} else {
				logger.info("You failed to upload because the file was empty.");
			}
			try{

			if (!img_url2.isEmpty()&&!img_url2.equals("")&&img_url2!=null&&img_url2.getSize()!=0) {
				// 获得上传时的文件名
				String temp_name = img_url2.getOriginalFilename();
				String postfix = temp_name.substring(temp_name.lastIndexOf("."), temp_name.length());
				file_name = UUID.randomUUID().toString() + postfix;
				filePath = super.getSession().getServletContext().getRealPath("")+"fileUpload"+File.separator+"job"+File.separator +file_name;
				logger.info(filePath);
				try {
					img_url2.transferTo(new File(filePath));
					logger.info("You successfully uploaded img_url2");
				} catch (Exception e) {
					logger.error("You failed to upload", e);
					map.put("flag", "3");
					return gson.toJson(map);
				}
				String realfliePath = "fileUpload" + File.separator + "job" + File.separator + file_name;		
				rework.setImg_url2(realfliePath);
			} 
			}catch(Exception e){
				logger.error("You failed to upload");
			}
			
			try{		
				if (!img_url3.isEmpty()&&!img_url3.equals("")&&img_url3!=null&&img_url3.getSize()!=0) {
					// 获得上传时的文件名
					String temp_name = img_url3.getOriginalFilename();
					String postfix = temp_name.substring(temp_name.lastIndexOf("."), temp_name.length());
					file_name = UUID.randomUUID().toString() + postfix;
					filePath = super.getSession().getServletContext().getRealPath("")+"fileUpload"+File.separator+"job"+File.separator +file_name;
					logger.info(filePath);
					try {
						img_url3.transferTo(new File(filePath));
						logger.info("You successfully uploaded img_url3");
					} catch (Exception e) {
						logger.error("You failed to upload", e);
						map.put("flag", "3");
						return gson.toJson(map);
					}
					String realfliePath = "fileUpload" + File.separator + "job" + File.separator + file_name;			
					rework.setImg_url3(realfliePath);
				}
			}catch(Exception e){
				logger.error("You failed to upload");
			}
			
			
			if(!img_url1.isEmpty()){
				rework.setJobitem(jobitem);
				rework.setRework_status(4);
				rework.setMemo(memo);	
				jobService.add_rework(rework);
			}
			
			// 添加工作项状态日志
			Jobitemstatus_Change jobitemstatus_change = new Jobitemstatus_Change();
			jobitemstatus_change.setJobitem(jobitem);
			jobitemstatus_change.setJobitem_status(4);
			jobitemstatus_change.setTime(new Date());
			jobitemstatus_change.setStatus(1);
			jobService.add_jobitemstatus_change(jobitemstatus_change);

			// 发送消息
			Message message = new Message();
			User sender = userService.getbyId(jobitem_user.getUser().getId());
			User receiver = userService.getbyId(jobitem_user.getJobitem().getJob().getUser().getId());
			message.setSender(sender);
			message.setReceiver(receiver);
			message.setJobitem(jobitem_user.getJobitem());
			message.setStatus(1);
			message.setReceiver_type(2);
			message.setIssystemmessage(1);
			message.setMessage("工人发起完工请求");
			message.setCheckstatus(0);
			messageService.add_message(message);

			// 推送
			PushtoSingle.pushApp(receiver.getClientid(), message);
			if (receiver.getToken() != null && !("undefined").equals(receiver.getToken())) {
				PushtoSingle.pushApp(receiver.getToken(), message);
			}
			map.put("flag", "1");
		} catch (Exception e) {
			if (filePath != null) {
				new File(filePath).delete();
			}
			map.put("flag", "0");
			logger.error("工人返工完工请求失败", e);
		}
		String str = gson.toJson(map);
		return str;
	}

	// 前台，手动确认完工
	@RequestMapping(value = "/end_response.do", method = RequestMethod.GET)
	@ResponseBody
	public String end_response(String jobitem_user_id, String jsoncallback) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			Jobitem_User jobitem_user = jobService.getbyId_jobitem_user(Integer.valueOf(jobitem_user_id));
			Jobitem jobitem = jobService.getbyId_jobitem(jobitem_user.getJobitem().getId());
			jobitem.setJobitem_status(-1);
			jobitem.setEnd_date(new Date());
			jobitem_user.setJobitem(jobitem);
			jobService.update_jobitem_user(jobitem_user);

			// 添加工作项状态日志
			Jobitemstatus_Change jobitemstatus_change = new Jobitemstatus_Change();
			jobitemstatus_change.setJobitem(jobitem);
			jobitemstatus_change.setJobitem_status(-1);
			jobitemstatus_change.setTime(new Date());
			jobitemstatus_change.setStatus(1);
			jobService.add_jobitemstatus_change(jobitemstatus_change);

			// 发送消息
			Message message = new Message();
			User receiver = userService.getbyId(jobitem_user.getUser().getId());
			User sender = userService.getbyId(jobitem_user.getJobitem().getJob().getUser().getId());
			message.setSender(sender);
			message.setReceiver(receiver);
			message.setJobitem(jobitem_user.getJobitem());
			message.setStatus(1);
			message.setReceiver_type(1);
			message.setIssystemmessage(1);
			message.setMessage("工长已确认完工");
			message.setCheckstatus(0);
			messageService.add_message(message);

			// 推送
			PushtoSingle.pushApp(receiver.getClientid(), message);
			if (receiver.getToken() != null && !("undefined").equals(receiver.getToken())) {
				PushtoSingle.pushApp(receiver.getToken(), message);
			}

			map.put("flag", "1");
		} catch (Exception e) {
			logger.error("确认完工失败", e);
			map.put("flag", "0");
		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}

	// 前台，返工
	@RequestMapping(value = "/rework.do", method = RequestMethod.POST)
	@ResponseBody
	public String rework(String jobitem_user_id, @RequestParam("img_url1") MultipartFile img_url1,MultipartFile img_url2,MultipartFile img_url3, String memo) {
		Map<String, String> map = new HashMap<String, String>();
		String filePath = null, file_name = null;
		Gson gson = new Gson();
		try {
			Jobitem_User jobitem_user = jobService.getbyId_jobitem_user(Integer.valueOf(jobitem_user_id));
			Jobitem jobitem = jobService.getbyId_jobitem(jobitem_user.getJobitem().getId());
			jobitem.setJobitem_status(5);
			jobitem_user.setJobitem(jobitem);
			jobitem_user.setRework_status(1);
			jobService.update_jobitem_user(jobitem_user);
			Rework rework = new Rework();
			if (!img_url1.isEmpty()) {
				// 获得上传时的文件名
				String temp_name = img_url1.getOriginalFilename();
				String postfix = temp_name.substring(temp_name.lastIndexOf("."), temp_name.length());
				file_name = UUID.randomUUID().toString() + postfix;
				filePath = super.getSession().getServletContext().getRealPath("")+"fileUpload"+File.separator+"job"+ File.separator + file_name;
				logger.info(filePath);
				try {
					img_url1.transferTo(new File(filePath));
					logger.info("You successfully uploaded img_url1");
				} catch (Exception e) {
					logger.error("You failed to upload", e);
					map.put("flag", "3");
					return gson.toJson(map);
				}
				String realfliePath = "fileUpload" + File.separator + "job" + File.separator + file_name;
				rework.setImg_url(realfliePath);
			} else {
				logger.info("You failed to upload because the file was empty.");
			}
			try{
			if (!img_url2.isEmpty()&&!img_url2.equals("")&&img_url2!=null&&img_url2.getSize()!=0) {
				// 获得上传时的文件名
				String temp_name = img_url2.getOriginalFilename();
				String postfix = temp_name.substring(temp_name.lastIndexOf("."), temp_name.length());
				file_name = UUID.randomUUID().toString() + postfix;
				filePath = super.getSession().getServletContext().getRealPath("")+File.separator+"fileUpload"+File.separator+"job"+ File.separator + file_name;
				logger.info(filePath);
				try {
					img_url2.transferTo(new File(filePath));
					logger.info("You successfully uploaded img_url2");
				} catch (Exception e) {
					logger.error("You failed to upload", e);
					map.put("flag", "3");
					return gson.toJson(map);
				}
				String realfliePath = "fileUpload" + File.separator + "job" + File.separator + file_name;
				rework.setImg_url2(realfliePath);
			} 
			}catch(Exception e){
				logger.error("You failed to upload");
			}
			try{
			if (!img_url3.isEmpty()&&!img_url3.equals("")&&img_url3!=null&&img_url3.getSize()!=0) {
				// 获得上传时的文件名
				String temp_name = img_url3.getOriginalFilename();
				String postfix = temp_name.substring(temp_name.lastIndexOf("."), temp_name.length());
				file_name = UUID.randomUUID().toString() + postfix;
				filePath = super.getSession().getServletContext().getRealPath("")+File.separator+"fileUpload"+File.separator+"job"+ File.separator + file_name;
				logger.info(filePath);
				try {
					img_url3.transferTo(new File(filePath));
					logger.info("You successfully uploaded img_url3");
				} catch (Exception e) {
					logger.error("You failed to upload", e);
					map.put("flag", "3");
					return gson.toJson(map);
				}
				String realfliePath = "fileUpload" + File.separator + "job" + File.separator + file_name;
				rework.setImg_url3(realfliePath);
			}
			}catch(Exception e){
				logger.error("You failed to upload");
			}
			if(!img_url1.isEmpty()){
				
                rework.setJobitem(jobitem);
				rework.setRework_status(4);
				rework.setMemo(memo);
				jobService.add_rework(rework);
			}
			
			// 发送消息
			Message message = new Message();
			User receiver = userService.getbyId(jobitem_user.getUser().getId());
			User sender = userService.getbyId(jobitem_user.getJobitem().getJob().getUser().getId());
			message.setSender(sender);
			message.setReceiver(receiver);
			message.setJobitem(jobitem_user.getJobitem());
			message.setStatus(1);
			message.setIssystemmessage(1);
			message.setMessage("工长请求返工");
			message.setCheckstatus(0);
			messageService.add_message(message);

			// 推送
			PushtoSingle.pushApp(receiver.getClientid(), message);
			if (receiver.getToken() != null && !("undefined").equals(receiver.getToken())) {
				PushtoSingle.pushApp(receiver.getToken(), message);
			}

			map.put("flag", "1");
		} catch (Exception e) {
			if (filePath != null) {
				new File(filePath).delete();
			}
			logger.error("工长返工失败", e);
			map.put("flag", "0");
		}
		String str = gson.toJson(map);
		return str;
	}

	// 前台，工人接单列表
	@RequestMapping(value = "/show_jobitem_users.do", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String show_jobitem_users(String user_id, String jsoncallback) {
		Gson gson = new Gson();
		Map<String, String> map = new HashMap<String, String>();
		Map<String, Object> map1 = new HashMap<String, Object>();
		List<Object> list = new ArrayList<Object>();
		List<Object> list1 = new ArrayList<Object>();
		map.put("user_id", user_id);
		map.put("status", String.valueOf(1));
		String json = "";
		try {
			if (user_id != null) {
				list = jobService.searchJobitem_Users(map);
				if (list != null) {			
   				for (int i = 0; i<list.size(); i++) {
						Map<String, Object> map2 = new HashMap<String, Object>();
						Jobitem_User jobitem_user = new Jobitem_User();
						jobitem_user = (Jobitem_User) list.get(i);
						Jobitem jobitem = new Jobitem();
						jobitem = jobitem_user.getJobitem();
						Set<Skill> skills = new HashSet<Skill>();
						skills = jobService.getbyjobitem_id_skill(jobitem.getId());
						map2.put("jobitem_user", jobitem_user);
						map2.put("skills", skills);
						list1.add(map2);
					}
				}
				map1.put("msg", list1);
				map1.put("flag", "1");
			} else {
				logger.info("查询工人接单列表,user_id为空");
				map1.put("flag", "0");
			}
		} catch (Exception e) {
			logger.error("查询工人接单列表失败", e);
			map1.put("flag", "0");
		}
		json = gson.toJson(map1);
		return jsoncallback + "(" + json + ")";
	}

	// 前台，工人历史接单列表
	@RequestMapping(value = "/show_jobitem_users_his.do", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String show_jobitem_users_his(String user_id, String jsoncallback) {
		Gson gson = new Gson();
		Map<String, String> map = new HashMap<String, String>();
		Map<String, Object> map1 = new HashMap<String, Object>();

		List<Object> list = new ArrayList<Object>();
		List<Object> list1 = new ArrayList<Object>();
		map.put("user_id", user_id);
		String json = "";
		try {
			if (user_id != null) {
				list = jobService.searchJobitem_Users_his(map);
				if (list != null) {
					for (int i = 0; i < list.size(); i++) {
						Map<String, Object> map2 = new HashMap<String, Object>();
						Jobitem_User jobitem_user = new Jobitem_User();
						jobitem_user = (Jobitem_User) list.get(i);
						Jobitem jobitem = new Jobitem();
						jobitem = jobitem_user.getJobitem();
						Set<Skill> skills = new HashSet<Skill>();
						skills = jobService.getbyjobitem_id_skill(jobitem.getId());

						map2.put("jobitem_user", jobitem_user);
						map2.put("skills", skills);
						list1.add(map2);
					}
				}
				map1.put("msg", list1);
				map1.put("flag", "1");
			} else {
				logger.info("查询工人接单列表,user_id为空");
				map1.put("flag", "0");
			}
		} catch (Exception e) {
			logger.error("查询工人接单列表失败", e);
			map1.put("flag", "0");
		}
		json = gson.toJson(map1);
		return jsoncallback + "(" + json + ")";
	}

	// 前台，工长发单列表
	@RequestMapping(value = "/show_jobs.do", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String show_jobs(String user_id, String county_code, String jsoncallback) {
		Gson gson = new Gson();
		Map<String, String> map = new HashMap<String, String>();
		Map<String, Object> map1 = new HashMap<String, Object>();
		List<Object> list1 = new ArrayList<Object>();
		List<Object> list2 = new ArrayList<Object>();
		map.put("user_id", user_id);
		map.put("status", "1");
		map.put("flag", "1");
		map.put("county_code", county_code);
		String json = "";
		Area area;
		int count = 0;
		try {
			list1 = jobService.searchJobs(map);
			if (list1.size() > 0) {
				for (int i = 0; i < list1.size(); i++) {
					count = 0;
					Job job = new Job();
					job = (Job) list1.get(i);
					map.put("job_id", String.valueOf(job.getId()));
					list2 = jobService.searchJobitems(map);
					for (int j = 0; j < list2.size(); j++) {
						Jobitem jobitem = new Jobitem();
						jobitem = (Jobitem) list2.get(j);
						if (jobitem.getJobitem_status() == -2) {
							count++;
						}
					}
					if (count == list2.size()) {
						job.setJob_status(1);
					}
					if (job.getArea() != null) {
						area = communityService.getbyCode(job.getArea().getPrevious_code());
						job.setAddress(communityService.getbyCode(area.getPrevious_code()).getName() + "-"
								+ area.getName() + "-" + job.getArea().getName());
					}
					jobService.update_job(job);
				}
			}
			map1.put("msg", list1);
			map1.put("flag", "1");
		} catch (Exception e) {
			logger.error("查询工长发单列表失败", e);
			map1.put("flag", "0");
		}
		json = gson.toJson(map1);
		return jsoncallback + "(" + json + ")";
	}

	// 前台，通过jobid，查看发布工作详情
	@RequestMapping(value = "/show_job_byid.do", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String show_job_byid(String job_id, String jsoncallback) {
		Map<String, String> map = new HashMap<String, String>();
		Map<String, Object> map1 = new HashMap<String, Object>();
		List<Object> list  = new ArrayList<Object>();
		List<Object> list1 = new ArrayList<Object>();
		List<Object> list2 = new ArrayList<Object>();
		Jobitem jobitem;
		Gson gson = new Gson();
		String json = "";
		map.put("status", "1");
		try {
			Job job = jobService.getbyId_job(Integer.valueOf(job_id));
			if (job != null) {
				map.put("job_id", String.valueOf(job.getId()));
				list1 = jobService.searchJobitems(map);
				for (int i = 0; i < list1.size(); i++) {
					jobitem = (Jobitem) list1.get(i);
					Map<String, Object> map2 = new HashMap<String, Object>();
					map2.put("jobitem", jobitem);
					Set<Skill> skills = new HashSet<Skill>();
					skills = jobService.getbyjobitem_id_skill(jobitem.getId());
					map2.put("skills", skills);

					map.put("jobitem_id", String.valueOf(jobitem.getId()));
					list2 = jobService.searchJobitem_Users(map);
					if (list2 != null) {
						map2.put("jobitem_users", list2);
					} else {
						map2.put("jobitem_users", " ");
					}
					list.add(map2);
				}
			}
			map1.put("msg", list);
			map1.put("flag", "1");
		} catch (Exception e) {
			e.printStackTrace();
			map1.put("flag", "0");
			logger.error("查看发布工作详情", e);
		}
		json = gson.toJson(map1);
		return jsoncallback + "(" + json + ")";
	}

	// 前台，首页，显示全部
	@RequestMapping(value = "/show_jobitems.do", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String show_jobitems(String user_id, String county_code, String page_num, String string, String jobtype_id,
			String jsoncallback) {
		Map<String, String> map = new HashMap<String, String>();
		Map<String, Object> map1 = new HashMap<String, Object>();

		List<Object> list2 = new ArrayList<Object>();
		Gson gson = new Gson();
		PageBean pageBean;
		// 基本条件
		map.put("county_code", county_code);
		map.put("release_status", "1");
		map.put("j_status", "0_2");
		map.put("user_id", user_id);
		map.put("status", "1");
		// 搜索框
		map.put("jobtype_name", string);
		map.put("community_name", string);
		// 工种筛选
		map.put("jobtype_id", jobtype_id);
		if (page_num == "" || page_num == null) {
			page_num = "1";
		}
		try {
			pageBean = jobService.searchJobitems_index(map, 10, Integer.valueOf(page_num));
			List<Object> list = pageBean.getList();
			if (list != null) {
				for (int i = 0; i < list.size(); i++) {
					Map<String, Object> map2 = new HashMap<String, Object>();
					// 添加技能
					Set<Skill> skills = new HashSet<Skill>();
					Jobitem jobitem = (Jobitem) list.get(i);
					skills = jobService.getbyjobitem_id_skill(jobitem.getId());
					map2.put("skills", skills);
					map2.put("jobitem", jobitem);
					// 接单人数
					List<Jobitem_User> list1 = new ArrayList<Jobitem_User>();
					list1 = jobService.getbyjobitem_id_jobitem_user(jobitem.getId());
					map2.put("user_num", list1.size());
				
					list2.add(map2);
				}
			}
			map1.put("msg", list2);
			map1.put("flag", "1");
			map1.put("page_count", pageBean.getTotalPage());
		} catch (Exception e) {
			logger.error("首页显示全部发单失败", e);
			map1.put("flag", "0");
		}
		String str = gson.toJson(map1);
		return jsoncallback + "(" + str + ")";
	}

	// 前台，根据jobitemid，输出其详细信息
	@RequestMapping(value = "/show_jobitem_byid.do", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String show_jobitem_byid(String jobitem_id, String jsoncallback) {
		Jobitem jobitem = null;
		Gson gson = new Gson();
		Map<String, Object> map1 = new HashMap<String, Object>();
		Set<Skill> skills = new HashSet<Skill>();
		try {
			jobitem = jobService.getbyId_jobitem(Integer.valueOf(jobitem_id));
			skills = jobService.getbyjobitem_id_skill(jobitem.getId());
			map1.put("skills", skills);
			map1.put("msg", jobitem);
			map1.put("flag", "1");
		} catch (Exception e) {
			logger.error("查看工作项信息失败", e);
			map1.put("flag", "0");
		}
		String str = gson.toJson(map1);
		return jsoncallback + "(" + str + ")";
	}

	// 前台，返回工长发单确认完工最近倒计时
	@RequestMapping(value = "/jobitem_ensureend.do", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String jobitem_ensureend(String user_id, String jsoncallback) {
		Gson gson = new Gson();
		Map<String, String> map = new HashMap<String, String>();
		Map<String, Object> map1 = new HashMap<String, Object>();
		Map<String, Object> map2 = new HashMap<String, Object>();
		Map<String, Object> map3 = new HashMap<String, Object>();
		List<Object> list = new ArrayList<Object>();
		List<Object> list1 = new ArrayList<Object>();
		map.put("user_id", user_id);
		map.put("status", "1");
		map.put("flag", "1");
		map2.put("time", null);
		String json = "";
		try {
			list = jobService.searchJobs(map);
			if (list != null) {
				for (int i = 0; i < list.size(); i++) {
					Job job = (Job) list.get(i);
					map.put("job_id", String.valueOf(job.getId()));
					map.put("jobitem_status", String.valueOf(4));

					list1 = jobService.searchJobitems(map);
					if (list1.size() != 0) {
						Jobitem jobitem = (Jobitem) list1.get(0);
						map2.put("jobitem_id", String.valueOf(jobitem.getId()));
						map2.put("time", jobitem.getEnd_request_date());

						if (jobitem.getEnd_request_date().compareTo((Date) map2.get("time")) < 0) {
							map2.put("jobitem_id", String.valueOf(jobitem.getId()));
							map2.put("time", jobitem.getEnd_request_date());
						}
					}
				}
			}
			if (map2.get("time") != null) {
				Calendar c = Calendar.getInstance();
				c.setTime((Date) map2.get("time"));
				map3.put("year", c.get(Calendar.YEAR));
				map3.put("month", c.get(Calendar.MONTH) + 1);
				map3.put("day", c.get(Calendar.DAY_OF_MONTH));
				map3.put("hour", c.get(Calendar.HOUR_OF_DAY));
				map3.put("minute", c.get(Calendar.MINUTE));
				map3.put("second", c.get(Calendar.SECOND));
				map2.put("time", map3);
				map1.put("msg", map2);
				map1.put("flag", "1");
			} else {
				map1.put("flag", "0");
			}

		} catch (Exception e) {
			logger.error("获取订单倒计时失败", e);
			map1.put("flag", "0");
		}
		json = gson.toJson(map1);
		return jsoncallback + "(" + json + ")";
	}

	// 前台，修改工作项信息
	@RequestMapping(value = "/update_jobitem.do", method = RequestMethod.GET)
	@ResponseBody
	public String update_jobitem(String id, String job_id, String jobtype_id, String skills_id, String decoration_type,
			String area, String unit, String salary, String urgent_status, String urgent_fee, String pre_start_date,
			String jsoncallback) {
		System.out.println("skills_id"+skills_id+"area"+area);
		Map<String, String> map = new HashMap<String, String>();

		try {
			Jobitem jobitem = jobService.getbyId_jobitem(Integer.valueOf(id));
			Job job = jobService.getbyId_job(Integer.valueOf(job_id));
			Jobitem_Skill jobitem_Skill=jobService.getbyId_jobitem_skill((Integer.valueOf(id)));
			if (skills_id != null && skills_id != "") {
				String[] skillid_array = skills_id.split("_");
				if (Integer.valueOf(id)!= 0) {
					jobService.delete(Integer.valueOf(id));
					jobService.add_skills(Integer.valueOf(id), skillid_array);
				}
			}
			if (decoration_type != null && decoration_type != "") {
				job.setDecoration_type(Integer.valueOf(decoration_type));
			}
			if (jobtype_id != null && jobtype_id != "") {
				jobitem.setJobtype(jobtypeService.getbyId_jobtype(Integer.valueOf(jobtype_id)));// 根据工种ID查找工种
			}
			jobitem.setJob(job);
			if (pre_start_date != null && pre_start_date != "") {
				DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
				jobitem.setPre_start_date(format1.parse(pre_start_date));
			}
			if (area != null && area != "") {
				jobitem.setArea(Double.valueOf(area));
			}
			if (unit != null && unit != "") {
				jobitem.setUnit(Integer.valueOf(unit));
			}
			if (salary != null && salary != "") {
				jobitem.setSalary(Double.valueOf(salary));
			}
			if (urgent_status != null && urgent_status != "") {
				jobitem.setUrgent_status(Integer.valueOf(urgent_status));
			}
			if (urgent_fee != null && urgent_fee != "") {
				jobitem.setUrgent_fee(Double.valueOf(urgent_fee));
			}

			jobService.update_jobitem(jobitem);
			map.put("flag", "1");
			map.put("jobid", String.valueOf(job.getId()));
			
			map.put("jobitemid", String.valueOf(jobitem.getId()));
		} catch (Exception e) {
			logger.error("修改发单信息失败", e);
			map.put("flag", "0");
		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}
}
